import { AppConfig } from '../types';

/**
 * 配置服务
 * 负责与后端配置API的通信
 */
export class ConfigService {
  private static readonly BASE_URL = 'http://localhost:3001/api/config';

  /**
   * 获取配置
   */
  static async getConfig(): Promise<AppConfig> {
    try {
      // 添加缓存控制参数，确保获取最新数据
      const response = await fetch(`${this.BASE_URL}?t=${Date.now()}`, {
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache'
        }
      });
      const result = await response.json();
      
      if (!result.success) {
        throw new Error(result.error || '获取配置失败');
      }
      
      return result.data;
    } catch (error) {
      console.error('获取配置失败:', error);
      throw error;
    }
  }

  /**
   * 保存配置
   */
  static async saveConfig(config: AppConfig): Promise<void> {
    try {
      const response = await fetch(`${this.BASE_URL}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(config),
      });
      
      const result = await response.json();
      
      if (!result.success) {
        throw new Error(result.error || '保存配置失败');
      }
    } catch (error) {
      console.error('保存配置失败:', error);
      throw error;
    }
  }



  /**
   * 重置配置为默认值
   */
  static async resetConfig(): Promise<void> {
    try {
      const response = await fetch(`${this.BASE_URL}/reset`, {
        method: 'POST',
      });
      
      const result = await response.json();
      
      if (!result.success) {
        throw new Error(result.error || '重置配置失败');
      }
    } catch (error) {
      console.error('重置配置失败:', error);
      throw error;
    }
  }
}